package cn.com.open.ms.ecgpaasdatarest.exception;

import cn.com.open.ms.ecgpaasdatarest.common.Result;
import cn.com.open.ms.ecgpaasdatarest.common.ResultCode;
import cn.com.open.ms.ecgpaasdatarest.utils.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理
 */
@ControllerAdvice
public class ExceptionProcess {

    private static final Logger LOG = LoggerFactory.getLogger(ExceptionProcess.class);

    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseEntity<String> serviceException(ServiceException e, HttpServletResponse response) {
        LOG.error(e.getMessage(), e);
        Result result = new Result(e.getMessage(),System.currentTimeMillis(),null);
        return new ResponseEntity<>(GsonUtil.toJson(result),HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    public ResponseEntity<String> noHandlerFound(NoHandlerFoundException e, HttpServletRequest request) {
        LOG.error(e.getMessage(), e);
        Result result = new Result("接口 [" + request.getRequestURI() + "] 不存在",System.currentTimeMillis(),null);
        return new ResponseEntity<>(GsonUtil.toJson(result),HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(ServletException.class)
    @ResponseBody
    public ResponseEntity<String> servletException(ServletException e) {
        LOG.error(e.getMessage(), e);
        Result result = new Result(e.getMessage(),System.currentTimeMillis(),null);
        return new ResponseEntity<>(GsonUtil.toJson(result),HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public ResponseEntity<String> processException(Throwable e, HttpServletRequest request) {
        LOG.error(e.getMessage(), e);
        Result result = new Result("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员",System.currentTimeMillis(),null);
        return new ResponseEntity<>(GsonUtil.toJson(result),HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
